<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';
import { $t } from '@vben/locales';
import { useVbenForm } from '#/adapter/form';
import { postAdminRoles, putAdminRoles } from '#/api/admin/roles';

const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'name',
      label: $t('admin.roleName'),
      rules: 'required',
    },

    {
      component: 'Select',
      defaultValue: '',
      componentProps: {
        class: 'w-full',
        placeholder: $t('page.common.Please Select'),
        options: [
          {
            value: 'admin',
            label: $t('admin.administrator'),
          },
        ],
      },
      fieldName: 'type',
      label: $t('page.common.Category'),
      rules: 'required',
    },
    {
      component: 'Switch',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: $t('admin.Enable'),
        unCheckedChildren: $t('admin.Disbale'),
      },
      fieldName: 'status',
      label: $t('page.common.Status'),
      rules: 'required',
    },
    {
      component: 'Textarea',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'remark',
      label: $t('admin.Remark'),
    },
  ],
  showDefaultActions: false,
});
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    formModalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: any = formModalApi.getData();
      if (values) {
        formApi.setValues(values);
      }
    }
  },
});

async function onSubmit(values: any) {
  function showMsg(msg: string) {
    message.success(msg);
    formModalApi.setData({ isUpdata: true });
    formModalApi.close();
  }

  if (values.id) {
    const { msg } = await putAdminRoles(values.id, values);
    showMsg(msg);
  } else {
    const { msg } = await postAdminRoles(values);
    showMsg(msg);
  }
}
</script>
<template>
  <Modal class="w-3/5">
    <Form />
  </Modal>
</template>

<style lang="scss" scoped></style>
